package org.hj.modules.generatecode.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.io.IOUtils;
import org.hj.common.annotation.AutoLog;
import org.hj.common.api.vo.Result;
import org.hj.modules.generatecode.entity.ViewModule;
import org.hj.modules.generatecode.entity.ViewUiproperties;
import org.hj.modules.generatecode.service.IViewModuleService;
import org.hj.modules.generatecode.service.IViewUipropertiesService;
import org.hj.modules.generatecode.util.FreeMarkerTemplateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.hj.modules.generatecode.controller.CodeGenerateController.replaceUnderLineAndUpperCase;

/**
 * @author gbw
 * 2020/7/21
 */
@Slf4j
@Api(tags = "UI属性")
@RestController
@RequestMapping("/generatecode")
public class ReViewController {
    @Autowired
    private IViewModuleService viewModuleService;

    @Autowired
    private IViewUipropertiesService viewUipropertiesService;
    /**
     *表单预览代码生成
     *
     * @param
     * @return
     */
    //@AutoLog(value = "表单预览代码生成")
    @ApiOperation(value = "表单预览代码生成", notes = "表单预览代码生成")
    @GetMapping(value = "/reViewForm")
    public Result reViewForm(@RequestParam(name = "tableName", required = true) String tableName ,
                             @RequestParam(name = "parentId", required = true) String parentId ,
                          HttpServletRequest request, HttpServletResponse response){
        Result<String> result = new Result<>();
        try {
            String s = generateFileByTemplate("ReViewVueModal.ftl", tableName,parentId);

            if("A01".equals(s)){
                result.setSuccess(false);
                result.setResult(s);
                return result;
            }
            result.setResult(s);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     *列表预览代码生成
     *
     * @param
     * @return
     */
    //@AutoLog(value = "列表预览代码生成")
    @ApiOperation(value = "列表预览代码生成", notes = "列表预览代码生成")
    @GetMapping(value = "/reViewList")
    public Result reViewList(@RequestParam(name = "tableName", required = true) String tableName ,
                             @RequestParam(name = "parentId", required = true) String parentId ,

                             HttpServletRequest request, HttpServletResponse response){
        Result<String> result = new Result<>();

        try {
            String s = generateFileByTemplate("ReViewVueList.ftl", tableName,parentId);

            if("A01".equals(s)){
                result.setSuccess(false);
                result.setResult(s);
                return result;
            }
            result.setResult(s);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }



    /**
     *表单预览代码生成
     *
     * @param
     * @return
     */
    //@AutoLog(value = "表单预览代码生成")
    @ApiOperation(value = "表单预览代码生成", notes = "表单预览代码生成")
    @GetMapping(value = "/reViewFormDetailed")
    public Result reViewFormDetailed(@RequestParam(name = "tableName", required = true) String tableName ,
                             @RequestParam(name = "parentId", required = true) String parentId ,
                             HttpServletRequest request, HttpServletResponse response){
        Result<String> result = new Result<>();

        try {
            String s = generateFileByTemplate("detailed/vue/modules/ReViewVueModal.ftl", tableName,parentId);

            if("A01".equals(s)){
                result.setSuccess(false);
                result.setResult(s);
                return result;
            }
            result.setResult(s);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    private String generateFileByTemplate(final String templateName, String tableName,String parentId) throws Exception {

        Map<String, Object> dataMap = new HashMap<>();

        //查询表设置
        QueryWrapper<ViewModule> wrapper = new QueryWrapper<>();
        //wrapper.eq("view_maintable", tableName);
        wrapper.eq("id", parentId);
        ViewModule viewModule= viewModuleService.getOne(wrapper);
        //查询字段设置
        QueryWrapper<ViewUiproperties> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ui_table", tableName);
        queryWrapper.eq("parent_id", parentId);
        queryWrapper.orderByAsc("ui_order");
        List<ViewUiproperties> list = viewUipropertiesService.list(queryWrapper);

        queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("ui_table", tableName);
        queryWrapper.eq("ui_appview", "true");
        queryWrapper.eq("parent_id", parentId);
        queryWrapper.orderByAsc("ui_order");
        List<ViewUiproperties> formlist = viewUipropertiesService.list(queryWrapper);

        queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("ui_table", tableName);
        queryWrapper.eq("ui_form", "true");
        queryWrapper.eq("parent_id", parentId);
        queryWrapper.orderByAsc("ui_order");
        List<ViewUiproperties> list1 = viewUipropertiesService.list(queryWrapper);





        if(list.size()==0){
            return "A01";
        }
        dataMap.put("originalColumns", list);
        dataMap.put("formColumns", formlist);
        dataMap.put("viewModule", viewModule);
        dataMap.put("formList", list1);
        //转换后的表名，用来作为实体bean的文件名
        dataMap.put("entityName", replaceUnderLineAndUpperCase(tableName));




        /**
         * 判断是否是主明细表的生成模式，
         * 如果是，就查询对应的明细表的数据
         */

        if (viewModule.getDetailedTable() != null && viewModule.getDetailedTable().length() > 0) {
            //判断生成类型，0代表生成单表，1代表生成主明细表
            dataMap.put("generateType", "1");

            //查询字段设置,主明细表所有字段都查询出来
            QueryWrapper<ViewUiproperties> queryWrapperAll = new QueryWrapper<>();
            queryWrapperAll.eq("parent_id", parentId);
            queryWrapperAll.orderByAsc("ui_order");
            List<ViewUiproperties> listAll = viewUipropertiesService.list(queryWrapperAll);
            dataMap.put("allColumns", listAll);

            //明细表的表名，转换
            String[] detailedTable = viewModule.getDetailedTable().split(",");
            String str = Arrays.stream(detailedTable).map(s -> replaceUnderLineAndUpperCase(s)).collect(Collectors.joining(",", "", ""));
            dataMap.put("detailedTable", str.split(","));


        }




        Template template = FreeMarkerTemplateUtils.getTemplate(templateName);
        val stringWriter = new StringWriter();
        template.process(dataMap, stringWriter);

        System.err.println(stringWriter.toString());
        //返回字符串
       return stringWriter.toString();

    }



}
